<?php

define("COOKIE_USERNAME", '1a9sd8fas9d8fja293');

require_once('includes/database/DatabaseController.php');

/**
 * Description of Authenticator
 *
 * @author A.J. Janssen
 */
class Authenticator 
{
    private $authenticated = false;
    
    /** @var User */
    private $user;
    
    /** @var DataBaseController */
    private $dbc;
    
    function __construct($dbc)
    {
        session_start();
        $this->dbc = $dbc;
        //Check for active session
        if (!empty($_SESSION[COOKIE_USERNAME]))
        {
            $username = $_SESSION[COOKIE_USERNAME];
            $user = $this->dbc->userExists($username);
            if ($user !== false)
            {
                $this->authenticated = true;
                $this->user = $user;
            }
        }
    }
    
    function tryLogin()
    {
        if(empty($_POST['userOrEmail']))
            return false;
    
        if(empty($_POST['password']))
            return false;
    
        //get username & password
        $username = trim($_POST['userOrEmail']);
        $password = trim($_POST['password']);
        
        if (strpos($username, '@') !== FALSE)
        {   //login by email adres, get username
            $username = $this->dbc->getUsernameByEmail($username);
            if (empty($username))
                return false;
        }
        //verify credentials
        $result = $this->dbc->verifyLogin($username, $password);
        if($result === false)
            return false;
        
        //proces login with username from DB
        $this->login($result);
        return true;
    }
    
    //Note: actual login (which includes setting $this->user) does not occur untill a new page is loaded
    private function login($username)
    {
         $_SESSION[COOKIE_USERNAME] = $username;
         $this->authenticated = true;
    }
    
    public function logout()
    {
        // Unset all of the session variables.
        $_SESSION = array();

        // Note: This will destroy the session, and not just the session data!
        if (ini_get("session.use_cookies")) 
        {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        
        session_destroy();
        
        $this->authenticated = false;
    }
    
    public function isAuthenticated()
    {
        return $this->authenticated;
    }
    
    public function getUser()
    {
        return $this->user;
    }
}

?>
